package com.wuzf.matcher;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

public class RetryLimitMatcher extends HashedCredentialsMatcher{
	
	private Cache<String, AtomicInteger> passwordRetryCache;
	
	public RetryLimitMatcher(CacheManager cacheManager) {		
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }
	
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		 String username = (String)token.getPrincipal(); 
		 //根据用户名获取缓存
		 AtomicInteger retryCount = passwordRetryCache.get(username);
		 //如果获取到的缓存为空则说明有五次机会，则置为0
		 //把用户名和失败次数放到缓存里面
	     if(null == retryCount) {
	         retryCount = new AtomicInteger(0);
	         passwordRetryCache.put(username, retryCount);
	     }
	     //如果次数大于5，则抛出异常，方法结束
	     if(retryCount.incrementAndGet() > 5) {  
	         //if retry count > 5 throw  
	         throw new ExcessiveAttemptsException();  
	     }  
	     //验证账号密码是否正确，如果正确则清空当前用户名的缓存，从0开始计算，正好也可以验证账号密码是否通过
	     boolean matches = super.doCredentialsMatch(token, info);  
	     if(matches) {  
	         //clear retry count  
	         passwordRetryCache.remove(username);  
	     }
	     return matches;
	}
}
